package net.byg.run;

import com.moandjiezana.toml.Toml;
import net.byg.model.FtpInfo;
import net.byg.task.UploadFilesRunTask;
import org.apache.commons.beanutils.BeanUtils;

import java.io.*;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;


public class UploadAssets {
    public static void main(String[] args) {
        ExecutorService fixedThreadPool = null;
        Map<String, Object> servers = null;
        try {
            String filePath = getConfigPath();
            File file = new File(filePath);
            if (!file.exists()) {
                InputStream inputStream = UploadAssets.class.getResourceAsStream("/ftp-client.toml");
                byte[] buffer = new byte[inputStream.available()];
                inputStream.read(buffer);

                OutputStream outStream = new FileOutputStream(file);
                outStream.write(buffer);
                System.out.println("\r\n请先修改配置文件！");
                return;
            }
            Toml toml = new Toml().read(new FileInputStream(filePath));
            Map<String, Object> map = toml.toMap();
            servers = (Map<String, Object>) map.get("servers");
            fixedThreadPool = Executors.newFixedThreadPool(servers.size());
            Iterator<Map.Entry<String, Object>> ite = servers.entrySet().iterator();
            while (ite.hasNext()) {
                Map.Entry<String, Object> entry = ite.next();
                FtpInfo ftpInfo = new FtpInfo();
                BeanUtils.populate(ftpInfo, (Map<String, Object>) entry.getValue());
                fixedThreadPool.execute(new UploadFilesRunTask(ftpInfo));
            }
            fixedThreadPool.shutdown();
            while (true) {
                if (fixedThreadPool.isTerminated()) {
                    System.out.println("\r\n任务结束！");
                    break;
                }
                Thread.sleep(200);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static String getConfigPath() {
        String filePath = System.getProperty("java.class.path");
        String pathSplit = System.getProperty("path.separator");//windows下是";",linux下是":"
        if (filePath.contains(pathSplit)) {
            filePath = filePath.substring(0, filePath.indexOf(pathSplit));
        } else if (filePath.endsWith(".jar")) {//截取路径中的jar包名,可执行jar包运行的结果里包含".jar"
            filePath = filePath.substring(0, filePath.lastIndexOf(File.separator) + 1);
        }
        filePath += File.separator + "ftp-client.toml";
        System.out.println("配置文件: " + filePath);
        return filePath;
    }
}
